package com.zhenhao.xsq.netsdk_demo;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zhenhao.xsq.R;
import com.sdk.NETDEV_DEV_ADDR_INFO_S;
import com.sdk.NETDEV_DISCOVERY_CALLBACK_PF;
import com.sdk.NETDEV_DISCOVERY_DEVINFO_S;
import com.sdk.NetDEVSDK;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

public class CDevDiscovery extends Activity{
    private ActionBar m_oActionBar;

    private static HashMap<String, NETDEV_DISCOVERY_DEVINFO_S> m_oDeviceist = new HashMap<>();

    private EditText m_oDiscoveryMacTxt;
    private EditText m_oDiscoverySnTxt;
    private EditText m_oDiscoveryIPAddrTxt;
    private EditText m_oDiscoveryUsernameTxt;
    private EditText m_oDiscoveryPasswordTxt;
    private EditText m_oDiscoverySubMaskTxt;
    private EditText m_oDiscoveryGatewayTxt;

    String[] szDevList;
    String strSelectMac = null;
    String strSelectDevSn = null;
    String strSelectIP = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discovery);
        m_oActionBar = super.getActionBar();
        initActionBar();

        m_oDiscoveryMacTxt = (EditText) findViewById(R.id.discoveryMac);
        m_oDiscoverySnTxt = (EditText) findViewById(R.id.discoverySn);
        m_oDiscoveryIPAddrTxt = (EditText) findViewById(R.id.discoveryIPAddr);
        m_oDiscoveryUsernameTxt = (EditText) findViewById(R.id.discoveryUsername);
        m_oDiscoveryPasswordTxt = (EditText) findViewById(R.id.discoveryPassword);
        m_oDiscoverySubMaskTxt = (EditText) findViewById(R.id.discoverySubMask);
        m_oDiscoveryGatewayTxt = (EditText) findViewById(R.id.discoveryGateway);

        Button BtnAutoDiscovery = (Button) findViewById(R.id.AutoDiscovery);
        Button BtnDiscoveryModifyIP = (Button) findViewById(R.id.discoveryModifyIP);

        final NetDEVSDK oNetDemo = new NetDEVSDK();
        oNetDemo.NETDEV_SetDiscoveryCallBack(CBDiscovery);
        BtnAutoDiscovery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                m_oDeviceist.clear();
                strSelectMac = null;
                strSelectDevSn = null;
                strSelectIP = null;
                String szBeginIP = "0.0.0.0";
                String szEndIP = "0.0.0.0";
                oNetDemo.NETDEV_Discovery(szBeginIP,szEndIP);
                try {
                    Thread.sleep(3000);
                    refreshListUI();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        BtnDiscoveryModifyIP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NETDEV_DEV_ADDR_INFO_S devAddrInfo = new NETDEV_DEV_ADDR_INFO_S();
                devAddrInfo.szDevMac = m_oDiscoveryMacTxt.getText().toString().trim();
                devAddrInfo.szDevSerailNum = m_oDiscoverySnTxt.getText().toString().trim();
                devAddrInfo.szIPv4Address = m_oDiscoveryIPAddrTxt.getText().toString().trim();
                devAddrInfo.szIPv4GateWay = m_oDiscoveryGatewayTxt.getText().toString().trim();
                devAddrInfo.szIPv4SubnetMask = m_oDiscoverySubMaskTxt.getText().toString().trim();
                devAddrInfo.szUserName = m_oDiscoveryUsernameTxt.getText().toString().trim();
                devAddrInfo.szPassword = m_oDiscoveryPasswordTxt.getText().toString().trim();

                if(devAddrInfo.szDevMac.isEmpty() ||
                   devAddrInfo.szDevSerailNum.isEmpty() ||
                   devAddrInfo.szIPv4Address.isEmpty() ||
                   devAddrInfo.szIPv4GateWay.isEmpty() ||
                   devAddrInfo.szIPv4SubnetMask.isEmpty() ||
                   devAddrInfo.szUserName.isEmpty() ||
                   devAddrInfo.szPassword.isEmpty()){
                    Toast.makeText(CDevDiscovery.this, "Invalid arguments", Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(CDevDiscovery.this, "modify start", Toast.LENGTH_SHORT).show();
                if(oNetDemo.NETDEV_ModifyDeviceAddr(devAddrInfo)){
                    Toast.makeText(CDevDiscovery.this, "modify succeed", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(CDevDiscovery.this, "modify failed", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public static NETDEV_DISCOVERY_CALLBACK_PF CBDiscovery = new NETDEV_DISCOVERY_CALLBACK_PF() {
        @Override
        public void invoke(NETDEV_DISCOVERY_DEVINFO_S stDevInfo) {
            if(!stDevInfo.szDevSerailNum.isEmpty()){
                m_oDeviceist.put(stDevInfo.szDevSerailNum,stDevInfo);
            }
        }
    };

    public void refreshListUI(){
        if(m_oDeviceist.size() == 0){
            return;
        }
        AlertDialog.Builder oBuilder = new AlertDialog.Builder(CDevDiscovery.this);
        oBuilder.setTitle("Device Num:" + m_oDeviceist.size());
        szDevList = new String[m_oDeviceist.size()];
        int dwCount = 0;
        Set<Map.Entry<String, NETDEV_DISCOVERY_DEVINFO_S>> entries = m_oDeviceist.entrySet();
        for(Map.Entry<String,NETDEV_DISCOVERY_DEVINFO_S> entry : entries){
            String strOut = "";
            strOut = "IP:" + entry.getValue().szDevAddr + "\n";
            strOut += "Module:" + entry.getValue().szDevModule + "\n";
            strOut += "Mac:" + entry.getValue().szDevMac + "\n";
            strOut += "sn:" + entry.getValue().szDevSerailNum;

            szDevList[dwCount++] = strOut;
        }

        //select first
        try {
            strSelectIP = szDevList[0].substring(szDevList[0].indexOf("IP:") + 3, szDevList[0].indexOf("Module:") - 1);
            strSelectMac = szDevList[0].substring(szDevList[0].indexOf("Mac:") + 4, szDevList[0].indexOf("sn:") - 1);
            strSelectDevSn = szDevList[0].substring(szDevList[0].indexOf("sn:") + 3);
        }catch (StringIndexOutOfBoundsException e){

        }

        String[] szDevListArr = new String[dwCount];
        System.arraycopy(szDevList, 0, szDevListArr, 0, dwCount);
        oBuilder.setSingleChoiceItems(szDevListArr, 0, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int witch) {
                try {
                    strSelectIP = szDevList[witch].substring(szDevList[witch].indexOf("IP:") + 3, szDevList[witch].indexOf("Module:") - 1);
                    strSelectMac = szDevList[witch].substring(szDevList[witch].indexOf("Mac:") + 4, szDevList[witch].indexOf("sn:") - 1);
                    strSelectDevSn = szDevList[witch].substring(szDevList[witch].indexOf("sn:") + 3);
                }catch (StringIndexOutOfBoundsException e){

                }
            }
        });
        oBuilder.setPositiveButton("select", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                if(strSelectMac == null ||
                strSelectDevSn == null ||
                strSelectIP == null){
                    return;
                }
                m_oDiscoveryIPAddrTxt.setText(strSelectIP);
                m_oDiscoveryMacTxt.setText(strSelectMac);
                m_oDiscoverySnTxt.setText(strSelectDevSn);
                m_oDiscoveryGatewayTxt.setText(strSelectIP.substring(0,strSelectIP.lastIndexOf(".") + 1) + "1");
            }
        });
        oBuilder.show();
    }

    private void initActionBar(){
        m_oActionBar.setDisplayShowHomeEnabled(false);
        m_oActionBar.setDisplayShowTitleEnabled(false);
        m_oActionBar.setDisplayHomeAsUpEnabled(true);
        m_oActionBar.setDisplayUseLogoEnabled(false);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();
        switch ( id ) {
            case android.R.id.home:
                final Intent intent = new Intent(this, CLocalDevLogin.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /* return key  */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {  // TODO Auto-generated method stub
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            exitBy2Click();
        }
        return false;
    }
    /* function of exit after 2 click  */
    private static Boolean isExit = false;
    private void exitBy2Click()
    {
        Timer tExit = null;
        if (isExit == false)
        {
            isExit = true;
            // prepare exiting
            Toast.makeText(this, "Press again to exit the app", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // cancel exit
                }
            }, 2000); // If the return key is not pressed for 2 seconds, the timer is started to cancel the task that was just executed
        }
        else
        {
            finish();

            System.exit(0);
        }
    }
}
